//指标分类管理
/* eslint-disable */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Divider, Tag, Input, Select, Button, message, Icon } from 'antd';
import { DndProvider, DragSource, DropTarget } from 'react-dnd';
import styles from './BackTarget.less';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import Filtrate from '../../components/common/Filtrate';
import request from '../../utils//request';
const { Search } = Input;
const { Option } = Select;
let dragingIndex = -1;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_1589202_syra9907zf.js',
});
class BodyRow extends React.Component {
    render() {
        const { isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props;

        const style = { ...restProps.style, cursor: 'move' };

        let { className } = restProps;
        if (isOver) {
            if (restProps.index > dragingIndex) {
                className += ' drop-over-downward';
            }
            if (restProps.index < dragingIndex) {
                className += ' drop-over-upward';
            }
        }
        // console.log(this.props)
        return connectDragSource(

            connectDropTarget(<tr {...restProps} className={className} style={style} />),
        );
    }
}

const rowSource = {
    beginDrag(props) {
        dragingIndex = props.index;
        return {
            index: props.index,
        };
    },
};

const rowTarget = {
    drop(props, monitor) {
        console.log(props, monitor.getItem())
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;//选中项的index

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
            return;
        }

        // Time to actually perform the action//实际操作时间
        props.moveRow(dragIndex, hoverIndex);
        //注意:我们正在修改监视器项!
        //一般来说，避免突变比较好，
        //但是这里是为了表现好
        //为了避免昂贵的索引搜索。
        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        monitor.getItem().index = hoverIndex;
    },
};


const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver(),
}))(
    DragSource('row', rowSource, connect => ({
        connectDragSource: connect.dragSource(),
    }))(BodyRow),
);

class BackTarget extends Component {
    state = {
        loading: false,
        equipmentId: '',
        options: [],//指标下拉框
        data: [],
        dataRight: [],
        companyId: '402880e5703d658801703d68a70e0000',
    };

    componentDidMount() {
        this.findListIndicatorClassify('402880e5703d658801703d68a70e0000')
    }

    findListIndicatorClassify = (pid) => {//查询指标下拉
        //localhost:8085/sx-client/sx/equipment/getListByCompanyId?companyId=402880e5703d658801703d68a70e0000


        request({
            url: `/sx-client/sx/equipment/getListByCompanyId?companyId=${pid}`,
            method: 'GET',
        }).then(data => {
            console.log(data)

            if (data.rc === 0) {
                data.ret.forEach(item => {
                    item.text = item.name
                    item.value = item.companyId
                });
                this.setState({
                    options: data.ret,
                    companyId: pid
                })

            } else {
                message.warning(`${data.err}`)
            }

        })
    }



    components = {
        body: {
            row: DragableBodyRow,
        },
    };

    moveRow = (dragIndex, hoverIndex) => {
        console.log('moveRow : ', dragIndex, hoverIndex)
        const { data } = this.state;
        const dragRow = data[dragIndex];
        /**
         * API: {$splice: array of arrays}
         * 同数组的 splice 方法
         *      数组 arrays 中包含的是所有需要执行的操作集合
         *      元素 array 中第一个元素代表下标，第二个元素代表需要删除的个数，第三个元素代表需要插入到 initialArray 中的的元素
         * 
         * PS:  1、可以在 arrays 中执行多个集合；
         *      2、两个操作不是同时执行，而是按顺序执行，后面的操作会在前面一个操作的执行结果上执行
         */

        this.setState(
            update(this.state, {
                data: {
                    $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],//[dragIndex, 1] 删除拖动列,[hoverIndex, 0, dragRow]将拖动列添加到移动结束的位置
                },
            }),
        );
    };
    onDelete = (text, record, index) => {
        console.log(text, record, index)
        this.setState(
            update(this.state, {
                dataRight: {
                    $splice: [[0, 0, this.state.data[index]]],//[dragIndex, 1] 删除拖动列,[hoverIndex, 0, dragRow]将拖动列添加到移动结束的位置
                },
                data: {
                    $splice: [[index, 1]],
                },
            }),
        );
    }

    onAddend = (text, record, index) => {
        console.log(text, record, index)
        if (this.state.data.length > 19) {
            message.warning('最多可选择20个指标!')
            return
        }

        this.setState(
            update(this.state, {
                data: {
                    $splice: [[this.state.data.length, 0, this.state.dataRight[index]]],//[dragIndex, 1] 删除拖动列,[hoverIndex, 0, dragRow]将拖动列添加到移动结束的位置
                },
                dataRight: {
                    $splice: [[index, 1]],
                },
            }),
        );
    }
    onSubmit = (page, size) => {//查询表格


        //localhost:8085/sx-client/sx/userkpiclassify/findTwoTable
        let params = {
            userId: 'admin',
            equipmentId: this.state.equipmentId
        }
        //localhost:8085/sx-client/sx/kpiclassify/getKpiClassifyList
        request({
            url: '/sx-client/sx/userkpiclassify/findTwoTable',
            method: 'POST',
            data: params
        }).then(data => {
            console.log(data)
            if (data.rc === 0) {
                this.setState({
                    data: data.ret.left,
                    dataRight: data.ret.right
                })
            }
        })



        // const params = {};
        // params.page = page;
        // params.rows = size;
        // const v = this.f1.getForm().getFieldsValue();
        // if (params.time) {
        //     params.startDateStr = moment(params.time[0]).format('YYYY-MM-DD');
        //     params.endDateStr = moment(params.time[1]).format('YYYY-MM-DD');
        // } else {
        // params.startDateStr = '';
        // params.endDateStr = '';
        // }
        // delete params.time;
        // this.setState({
        //     params
        // })
        // request({
        //     url: '/web/redstar/thirdpartymonitoring/queryThirdPartyMonitoringList',
        //     method: 'POST',
        //     data: params
        // }).then(data => {
        //     console.log(data)
        //     if (data.rc === 0) {
        //         let { dataSate } = this.state

        //         let aa = [...dataSate, ...data.ret.items]
        //         console.log(aa)
        //         this.setState({
        //             dataSate: aa,
        //             total: data.ret.rowCount,
        //         })
        //     }
        // })

    }
    //重置
    ResetForm = (page, size) => {

        this.onSubmit(1, 10)

    }

    handleChange = (v, val) => {
        console.log(v, val)
        this.setState({
            equipmentId: v
        })
    }

    onSearch = (value) => {
        this.setState({
            loading: true
        })
        let notInIdList = []
        this.state.data.forEach(item => {
            if (item) {
                notInIdList.push(item.id)
            }

        });
        let params = {
            equipmentId: this.state.equipmentId,
            name: value,
            notInIdList
        }
        request({
            url: '/sx-client/sx/induser/findRightList',
            method: 'POST',
            data: params
        }).then(data => {
            console.log(data)
            if (data.rc === 0) {
                this.setState({
                    dataRight: data.ret.twoList
                })

            } else {
                message.warning(`${data.err}`)
            }

            this.setState({
                loading: false
            })

        })

    }

    onSave = () => {
        if(this.state.data.length < 1){
            message.warning('请操作后保存!')
            return
        }
        let kpiClassifyIds = []
        this.state.data.forEach(item => {
            if (item) {
                kpiClassifyIds.push(item.id)
            }

        });
//localhost:8085/sx-client/sx/userkpiclassify/insertList

        let params = {
            kpiClassifyIds,
            userId: 'admin'
        }

        request({
            url: '/sx-client/sx/userkpiclassify/insertList',
            method: 'POST',
            data: params
        }).then(data => {
            if (data.rc === 0) {
                message.success('保存成功!')
                this.onSubmit()
            } else {
                message.warning(`${data.err}`)
            }

        })
    }
    render() {

        const { options } = this.state

        let width = document.body.clientWidth;
        const height = document.body.clientHeight;
        let containerHeight = '75vh';
        let tableHeight = 330;
        if (width > 1367) {
            tableHeight = 630;
            containerHeight = '80vh';
        }

        const columns = [
            {
                title: '序号',
                dataIndex: 'sum',
                key: 'sum',
                width: 50,
                align: 'center',
                render: (text, record, index) => <span>{index + 1}</span>
            },
            {
                title: '指标名称',
                dataIndex: 'name',
                key: 'name',
                width: 120,
                align: 'center',
            },
            {
                title: '指标单位',
                dataIndex: 'unit',
                key: 'unit',
                width: 80,
                align: 'center',
            },
            {
                title: '操作',
                dataIndex: 'address',
                key: 'address',
                width: 150,
                align: 'center',
                render: (text, record, index) => <span>

                    <IconFont type="iconshanchu" onClick={this.onDelete.bind(this, text, record, index)} style={{ fontSize: 20, cursor: 'pointer' }} />
                </span>
            },
        ];

        const columnsRight = [
            {
                title: '序号',
                dataIndex: 'sum',
                key: 'sum',
                width: 50,
                align: 'center',
                render: (text, record, index) => <span>{index + 1}</span>
            },
            {
                title: '指标名称',
                dataIndex: 'name',
                key: 'name',
                width: 120,
                align: 'center',
            },
            {
                title: '指标单位',
                dataIndex: 'unit',
                key: 'unit',
                width: 80,
                align: 'center',
            },
            {
                title: '操作',
                dataIndex: 'address',
                key: 'address',
                width: 150,
                align: 'center',
                render: (text, record, index) => <span>
                    {/* <a style={{ marginLeft: 5 }} href="javascript:;" >添加</a> */}
                    <IconFont type="iconxinzeng-" onClick={this.onAddend.bind(this, text, record, index)} style={{ fontSize: 20, cursor: 'pointer' }} />
                </span>
            },
        ];
        const items = [
            {
                type: 'select',
                label: '项目公司',
                paramName: 'indexNum',
                options: [
                    { text: '清能环保', value: '1' },
                    { text: '再生能源', value: '2' },
                    { text: '维尔利', value: '3' },
                    { text: '清运公司', value: '4' },

                ],
            },
            {
                type: 'select',
                label: '指标类型',
                paramName: 'index2Num',
                options: [
                    { value: '', text: '全部' },
                    ...this.state.options
                ],
            }
        ];
        return (

            <div className={styles.warp}>
                {/* <Filtrate
                    items={items}
                    ref={ref => { this.f1 = ref }}
                    submit={this.onSubmit.bind(this, 1, 10)}
                    ResetForm={this.ResetForm}
                /> */}
                <div className={styles.topBox}>
                    <span>项目公司：</span>
                    <Select size='small' defaultValue="402880e5703d658801703d68a70e0000" style={{ width: 170 }} onChange={this.findListIndicatorClassify}>
                        <Option value="402880e5703d658801703d68a70e0000">清能环保</Option>
                        <Option value="402880e5703d658801703d6904da0001">再生能源</Option>
                        <Option value="402880e5703d658801703d6978c40002">维尔利</Option>
                        <Option value="402880e5703d658801703d69c2230003">清运公司</Option>
                    </Select>
                    <span style={{ marginLeft: 10 }}>指标类型：</span>
                    <Select size='small' value={this.state.equipmentId} style={{ width: 170 }} onChange={this.handleChange}>
                        <Option value=''>全部</Option>
                        {
                            options.map((item) => {
                                return (
                                    <Option value={item.id}>{item.name}</Option>
                                )
                            })
                        }
                    </Select>

                    <Button size='small' style={{ marginLeft: 10 }} type="primary" onClick={this.onSubmit}>查询</Button>
                    <Button size='small' style={{ marginLeft: 10 }} >重置</Button>
                    <Button size='small' style={{ marginLeft: 10 }} className={styles.saveBtn} onClick={this.onSave}>保存</Button>

                </div>
                <div style={{ flex: 1, display: 'flex', height: containerHeight }}>

                    <div style={{ flex: 1, height: containerHeight, overflow: 'auto' }} className={styles.box}>
                        <div className={styles.title}>
                            <div style={{ display: 'flex', alignItem: 'center' }}><span className={styles.ciler}></span> 已选指标</div>  <span style={{ marginRight: 20 }}>{this.state.data.length}/20</span>
                        </div>
                        <DndProvider backend={HTML5Backend}>
                            <Table
                                scroll={{ y: tableHeight }}
                                pagination={false}
                                columns={columns}
                                dataSource={this.state.data}
                                components={this.components}
                                onRow={(record, index) => ({
                                    index,
                                    moveRow: this.moveRow,
                                })}
                            />
                        </DndProvider>
                    </div>

                    <Divider type="vertical" style={{ height: '100%' }} />
                    <div style={{ flex: 1, height: containerHeight }} className={styles.box}>
                        <div className={styles.title}>
                            <div style={{ display: 'flex', alignItem: 'center' }}><span className={styles.ciler}></span> 待选指标</div>
                            <div style={{ marginRight: 20 }}>
                                <Search
                                    placeholder="关键词"
                                    enterButton
                                    loading={this.state.loading}
                                    size="small"
                                    onSearch={this.onSearch}
                                />
                            </div>
                        </div>
                        <Table scroll={{ y: tableHeight }} columns={columnsRight} dataSource={this.state.dataRight} />

                    </div>
                </div>



            </div>
        )
    }


}

export default connect()(BackTarget)